package org.dcarew.halostatus.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.dcarew.halostatus.HaloStatusPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;

/**
 * Updates the Halo player count every two minutes.
 * 
 * @author Devon Carew
 */
public class HaloStatusUpdateJob
	extends Job
{
	private static final int TWO_MINUTES = 2 * 60 * 1000;
	
	public HaloStatusUpdateJob()
	{
		super("Halo Status Update");
		
		setPriority(Job.LONG);
		setUser(false);
		setSystem(true);
	}
	
	protected IStatus run(IProgressMonitor monitor)
	{
		updateHaloStatus();
		
		schedule(TWO_MINUTES);
		
		return Status.OK_STATUS;
	}

	private void updateHaloStatus()
	{
		try
		{
			URL 		url = new URL(HaloStatusPlugin.HALO_3_URL);
			InputStream in = url.openStream();
			String 		content = readString(in);
			
			String 		haloPlayerCount = getSpan(content, "ctl00_TopContentArea_bngLiveStats1_lblOnlinePlayers");
			
			HaloStatusPlugin.getPlugin().setPlayerCount(haloPlayerCount);
		}
		catch (IOException ioe)
		{
			//ioe.printStackTrace();
			
			HaloStatusPlugin.getPlugin().setPlayerCount("");
		}
	}

	private String readString(InputStream in)
		throws IOException
	{
		StringBuffer str = new StringBuffer();
		byte[] buffer = new byte[4096];
		
		int count = in.read(buffer);
		
		while (count >= 0)
		{
			str.append(new String(buffer, 0, count));
			count = in.read(buffer);
		}
		
		in.close();
		
		return str.toString();
	}

/*	
	<li>
	<div class="align_left" >Halo 3 Players Online:</div>
	<div class="align_right" >
	<span id="ctl00_TopContentArea_bngLiveStats1_lblOnlinePlayers">213,320</span></div></li>	
*/	
	
	private String getSpan(String content, String spanID)
	{
		int index = content.indexOf(spanID);
		if (index == -1) return null;
		content = content.substring(index + spanID.length());
		
		index = content.indexOf(">");
		if (index == -1) return null;
		content = content.substring(index + 1);
		
		index = content.indexOf("</span>");
		if (index == -1) return null;
		
		return content.substring(0, index);
	}
	
}
